# == Schema Information
# Schema version: 2
#
# Table name: users
#
#  id                   :integer       not null, primary key
#  email                :string(255)   not null
#  full_name            :string(255)   not null
#  password_hash        :string(255)
#  login_key            :string(255)
#  login_key_expires_at :datetime
#  created_at           :datetime
#  updated_at           :datetime
#

require 'digest/sha1'

class User < ActiveRecord::Base

  has_many :jobs

  validates_presence_of :email, :full_name, :message => 'can not be blank'[]

  validates_as_email :email, :message => 'is an invalid email'[]

  validates_uniqueness_of :email, :message => 'has already been taken'[]

  attr_reader :password

  validates_confirmation_of :password, :on => :create, :message => "doesn't match confirmation"[]
  validates_confirmation_of :password, :on => :update, :allow_nil => true

  validates_presence_of     :password_hash
  validates_length_of       :password, :minimum => 5, :allow_nil => true

  def password=(value)
    return if value.blank?
    write_attribute :password_hash, Digest::SHA1.hexdigest(value + PASSWORD_SALT)
    @password = value
  end

  def self.authenticate(email, password)
    find_by_email_and_password_hash(email,
                                    Digest::SHA1.hexdigest(password + PASSWORD_SALT))
  end


  def reset_login_key!
    self.login_key = Digest::SHA1.hexdigest(Time.now.to_s + password_hash.to_s + rand(123456789).to_s).to_s
    # this is not currently honored
    self.login_key_expires_at = Time.now.utc+1.year
    save!
    login_key
  end

end
